<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>绘制矩形</title>
    <style>
        canvas {
            display: block;
            margin: 10px auto 0;
            border: 1px solid orange;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="600" height="500">您的浏览器不支持canvans</canvas>
</body>
<script>
    const canvans = document.getElementById('canvas')
    const ctx = canvans.getContext('2d')

    const getPixelRatio = context => {
        return window.devicePixelRatio || 1
    }

    /**
     *  01. 放大canvas
     *  02. 在css中将宽高设置为原来的大小
     *  03. 考虑到内容的缩放，因此也需要将ctx 缩放
     * */
    const ratio = getPixelRatio()
    const oldWith = canvans.width
    const oldHeight = canvans.height
    // 放大canvas
    canvans.width = canvans.width * ratio
    canvans.height = canvans.height * ratio
    // css中设置为原来的大小
    canvans.style.width = oldWith + 'px'
    canvans.style.height = oldHeight + 'px'
    // 缩放ctx
    ctx.scale(ratio, ratio)

    const drawCircle = (x, y, r) => {
        ctx.beginPath()
        ctx.fillStyle = 'orange'
        ctx.arc(x, y, r, 0, Math.PI * 2)
        ctx.fill()
        ctx.closePath()
    }

    // 配置属性
    const wd = canvans.clientWidth * ratio
    const ht = canvans.clientHeight * ratio
    let x = y = 100
    const r = 20
    let xSpeed = 6
    let ySpeed = 4
    drawCircle(x, y, r)

    // 动起来
    setInterval(() => {
        ctx.clearRect(0, 0, wd, ht) // 清空画布
        if (x - r <= 0 || x + r >= wd) {
            xSpeed = -xSpeed
        }
        if (y - r <= 0 || y + r >= ht) {
            ySpeed = -ySpeed
        }
        x += xSpeed
        y += ySpeed
        drawCircle(x, y, r)
    }, 20)
</script>

</html>